package com.hgx.captcha.server.rest;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.hgx.captcha.server.response.PictureValidationVO;
import com.hgx.common.rest.response.CommonResponse;
import com.hgx.common.util.Base64Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.UUID;

@RestController("kaptchaController")
@RequestMapping(value = "kaptcha")
@Api(tags = "验证码工具")
public class KaptchaController {

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 生成验证码
     */
    @ApiOperation(value = "生成验证码")
    @ApiResponse(code = 500, message = "服务器出错，生成验证码失败")
    @GetMapping(value = "/get")
    public CommonResponse<PictureValidationVO> get(HttpServletRequest request, HttpServletResponse response) {

        String uuid = UUID.randomUUID().toString();

        logger.info("生成验证码[uuid:{}]", uuid);

        //验证码
        String rightCode = defaultKaptcha.createText();

        //生成图片加密后Base64字符串
        String imgBase64String;
        try {
            imgBase64String = getImgBase64String(rightCode);
        } catch (IOException e) {
            logger.info("生成验证码失败[uuid:{}]", uuid);
            return CommonResponse.error("服务器内部出错", null);
        }

        //返回响应内容
        PictureValidationVO pictureValidationVO = new PictureValidationVO();
        pictureValidationVO.setUuid(uuid);
        pictureValidationVO.setImgBase64(imgBase64String);

        logger.info("生成的验证码[uuid:{}]", uuid);
        return CommonResponse.ok(pictureValidationVO);
    }


    /**
     * 通过生成的验证码字符串生成图片Base64加密后字符串
     *
     * @param rightCode 验证码内容
     * @return
     * @throws IOException
     */
    private String getImgBase64String(String rightCode) throws IOException {
        //将验证码图片转换成字节流
        BufferedImage challenge = defaultKaptcha.createImage(rightCode);
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        ImageIO.write(challenge, "jpg", jpegOutputStream);
        return Base64Utils.getImageBase64String(jpegOutputStream.toByteArray());
    }


}